package com.atguigu.security.config;

import com.atguigu.security.entity.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Author: zhoufuzong
 * @Created: 2020-12-13 13:50:05
 * @Version: 1.1.0
 */

@Component  // 加入IOC 容器
public class MyUserDetailsService  implements UserDetailsService {

    @Autowired
    JdbcTemplate jdbcTemplate;

    // 总目标： 根据表单提交的用户名查询User对象，并装配角色，权限等信息

    @Override
    public UserDetails loadUserByUsername(
            // 表单提交的用户名
            String userName
    ) throws UsernameNotFoundException {


        // 1. 从数据库查询Admin对象
        String sql = "SELECT id,loginacct,userpswd,username,email,createtime FROM t_admin WHERE loginacct = ?";

        List<Admin> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Admin.class), userName);

        // 2. 给Admin设置角色权限信息
        Admin admin = list.get(0);
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));  // 角色
        authorities.add(new SimpleGrantedAuthority("UPDATE"));  // 权限

        // 3. 把admin对象和 authorities 封装到UserDetails 中
        String userpswd = admin.getUserPswd();
        return new User(userName,userpswd,authorities);



    }
}
